import os
import Gado.Database.Database as DB
import Gado.Database.DbFunctions as DBF

def scanImage():
    scanner = TwainBase()
    scanner.OpenScanner(window, "CanoScan 8800F")
    scanner.SD.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 600.0) 
    scanner.SD.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 600.0)
    print scanner.SD.GetCapability(twain.ICAP_CONTRAST)
    print scanner.SD.GetCapability(twain.ICAP_PIXELTYPE)
    scanner.SD.SetCapability(twain.ICAP_PIXELTYPE, twain.TWTY_UINT16, twain.TWPT_GRAY)
    scanner.AcquireByFile()
    watch = ''
    while(watch == ''):
        watch = scanner.PollForImage()
        time.sleep(.5)
   # scanner.Terminate()
    return
    conn.ping(True)
    cursor = DB.getCursorFromConn(conn)
    next_i = DBF.getNextNumForLocation(cursor, location_id)
    base_name = DBF.getBaseNameForLocation(cursor, location_id)
    name = "%s_%s" % (base_name, next_i)
    image_name = "%s.tiff" % name
    #raw_path = "G:\\raw_scans\\%s" % image_name
    raw_path = "%s" % image_name
    #print raw_path
    os.rename('TWAIN.tmp', raw_path)
    raw_path = "raw_scans\\\%s" % image_name
    artifact_id = DBF.makeNewArtifact(conn, cursor, location_id, next_i, base_name, user_id, 0)
    conn.commit()
    artifact_id = artifact_id
    DBF.addImageToArtifact(conn, cursor, artifact_id, name, raw_path, scanner_id, '1', user_id)
    conn.commit()
    cursor.close()

def scanImageLinux(conn, location_id, user_id, scanner_id):
    #sane.init()
    #scanner=sane.open('pixma:04A91901')
   # scanner.resolution = 600
   # scanner.mode = "Gray"
    #im = scanner.snap()
   # im.save("test.tiff")
    #im.show()
    call = "scanimage --format tiff --resolution 600 --mode Gray > output.tiff"
    os.system(call)
    conn.ping(True)
    cursor = DB.getCursorFromConn(conn)
    next_i = DBF.getNextNumForLocation(cursor, location_id)
    print "Next num is %s" % next_i
    next_i = DBF.checkIfNextiExists(cursor, next_i, location_id)
    print "Next num is %s" % next_i
    base_name = DBF.getBaseNameForLocation(cursor, location_id)
    name = "%s_%s" % (base_name, next_i)
    image_name = "%s.tiff" % name
    #raw_path = "G:\\raw_scans\\%s" % image_name
    raw_path = "%s" % image_name
    #print raw_path
    os.rename('output.tiff', raw_path)
    #raw_path = "raw_scans\\\%s" % image_name
    artifact_id = DBF.makeNewArtifact(conn, cursor, location_id, next_i, base_name, user_id, 0)
    DBF.addImageToArtifact(conn, cursor, artifact_id, name, raw_path, scanner_id, '1', user_id)
    conn.commit()
    cursor.close()
    return (artifact_id, next_i)
